package demo10.iterator.dinermergeri;

import java.util.Iterator;

/**
 * 餐厅菜单的迭代器
 * java迭代器
 * */
public class DinerMenuIterator implements Iterator<MenuItem>{
	MenuItem[] list;//菜单数组
   int position = 0;

public DinerMenuIterator(MenuItem[] list) {
	this.list = list;
}

@Override
public MenuItem next() {
	MenuItem menuItem = list[position];
	position = position + 1;
	return menuItem;
}

@Override
public boolean hasNext() {
	if (position >= list.length || list[position] == null) {
		return false;
	} else {
		return true;
	}
}
//注意在多线程中可能会有多个迭代器引用同一个对象，造成错误
@Override
public void remove() {
	if (position <= 0) {
		throw new IllegalStateException
			("你不能删除一个项目直到你已经做了至少一个next()");
	}
	if (list[position-1] != null) {
		for (int i = position-1; i < (list.length-1); i++) {
			list[i] = list[i+1];
		}
		list[list.length-1] = null;
	}
}}
